$(function () {
    //搜索框聚焦事件
    $(".t-search").focus(
        function () {
            $(this).next().hide().siblings(":last").show()
            $(".hot").show();
        }
    );
    $(".history ul li").mouseenter(function () {
        $(".t-search").unbind("blur")
    })
    $(".history ul").mouseleave(function () {
        console.log('555')
        $(".t-search").bind("blur",function () {
            $(this).val("").next().show().siblings(":last").hide()
        })
    })
    //搜索框失焦事件
    // $(".t-search").blur(function () {
    //     $(this).val("").next().show().siblings(":last").hide()
    // })
    $(".t-search").on("input change",function () {
        //隐藏搜索模块中热搜部分
        $(this).siblings(":last").children(":first").hide();
        var searchStr = $(".t-search").val();
        searchAssociate(searchStr)
    })
    //搜索框联想功能
    function searchAssociate(str) {
        if(str==""){
            return;
        }
        var searchData = "";
        $.ajax({
            url:"/search/"+str+"",
            type:"get",
            dataType:"json",
            success:function (result) {
                if (result.length==0){
                    $(".history ul").hide()
                    return
                }
                $.each(result,function (i,v) {
                    searchData+=
                        `<a href="`+window.location.href.split("/")[0]+`/course?typeId=`+v.id+`"><li>`+v.name+`</li></a>`
                })
                $(".history ul").show().empty().append(searchData);
            }
        })
    }
    //登录注册切换
    //登录页面
    function login(){
        console.log(666)
        $(".btn-login").addClass("active-title").next().removeClass("active-title");
        $(".js-loginWrap").show();
        $("#signup").hide().siblings("#register-signin").hide();
        $("#signup input[type='text']").empty().next().css({"visibility":"hidden"});
        $(".rl-modal-header").show();
        $(".reg-success1").hide();
    }
    //注册页面
    function register(){
        $(".btn-register").addClass("active-title").prev().removeClass("active-title");
        $("#signup").show();
        $(".js-loginWrap").hide().siblings("#register-signin").hide();
        $(".js-loginWrap input[type!='button']").val("").next().css({"visibility":"hidden"});
        $(".ipt-agreement").css({"visibility":"visible"});
        code = drawPic();
        $(".rl-modal-header").show();
    }
    function register1(){
        $(".btn-register").addClass("active-title").prev().removeClass("active-title");
        $("#register-signin").show();
        $(".js-loginWrap").hide().siblings("#signup").hide();
        $("#signup input[type!='button']").val("").next().css({"visibility":"hidden"});
        $(".ipt-agreement").css({"visibility":"visible"});
        code = drawPic();
    }

    $(".js-gotoLearn").click(function () {
        login();
    })
    $(".btn-login").click(function () {
        login();
    });
    $(".btn-register").click(function () {
        register();
    });
    //密码/短信登录切换
    $(".rlf-other").click(function () {
        var $state = $(this).attr("state");
        if($state==("loginPassword")){
            $(".js-phoneVerityBox").hide().children(":last").css({"visibility":"hidden"});
            $(".js-loginPassword").show().prev().children(":last").css({"visibility":"hidden"});;
            $(this).text("手机短信登录")
            $(".rlf-forget").show();
            $(this).attr("state","phoneVerityBox");
            $(".moco-btn-login").attr("loginway","pwd");
        }else{
            $(".js-phoneVerityBox").show().prev().prev().children(":last").css({"visibility":"hidden"});
            $(".js-loginPassword").hide().children(":last").css({"visibility":"hidden"});
            $(this).text("账号密码登录");
            $(".rlf-forget").hide();
            $(this).attr("state","loginPassword");
            $(".moco-btn-login").attr("loginway","code");
        }
    })
    //密码框密码是否可见切换
    $(".proclaim-btn").click(function () {
        var $hidefocus = $(this).attr("hidefocus");
        if ($hidefocus=="true"){
            $(this).attr("hidefocus","false").find("span").removeClass("glyphicon-eye-close").addClass("glyphicon-eye-open");
            $(this).next().attr("type","text");
        }else{
            $(this).attr("hidefocus","true").find("span").removeClass("glyphicon-eye-open").addClass("glyphicon-eye-close");
            $(this).next().attr("type","password");
        }
    })
    $("#js-signup-btn").click(function () {
        $(".modal-backdrop").show().next().show();
        register();
    })
    $("#js-signin-btn").click(function () {
        $(".modal-backdrop").show().next().show();
        login();
    })
    $(".rl-close").click(function () {
        $(".modal-backdrop").hide().next().hide();
        $(".reg-success1").hide();
    })
    $(".modal-backdrop").click(function () {
        $(".modal-backdrop").hide().next().hide();
        $(".reg-success1").hide();
    })
    //表单验证
    function phoneCheck(e){
        //手机号
        var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;//手机号验证
        var $phone = e.val();
        if (!myreg.test($phone)){
            e.next().empty().text("请输入正确的手机号").css({"visibility":"visible"})
            return false;
        }
        e.next().css({"visibility":"hidden"})
        return true;
    }
    //密码
    function pwdCheck(e){
        var patrn=/^([\w]|[.]){6,20}$/;//密码验证
        var $pwd = e.val();
        if (!patrn.test($pwd)) {
            e.next().css({"visibility":"visible"})
            return false;
        }
        e.next().css({"visibility":"hidden"});
        return true;
    }
    //短信验证码
    function checkNoCheck(e){
        var patrn=/^(\d){6}$/;//验证码
        var $pwd = e.val();
        if (!patrn.test($pwd)) {
            e.next().empty().text("请输入6位纯数字的短信验证码").css({"visibility":"visible"})
            return false;
        }
        e.next().css({"visibility":"hidden"});
        return true;
    }
    //图片验证码
    function pictureCheck(){
        var $mes = $("#register-pictureCheck").val().toLowerCase();
        if ($mes !=code.toLowerCase()){
            $("#register-pictureCheck").next().css({"visibility":"visible"})
            return false;
        }
        $("#register-pictureCheck").next().css({"visibility":"hidden"});
        return true;
    }
    $("#login-phone").on("input change",function () {
        if ($(this).val().length!=11){
            return
        }
            var r = checkUser($(this).val());
            if (r.result=="fail") {
                $(this).next().empty().text("账号未注册，请注册").css({"visibility":"visible"});
                $(".js-signin-send").css({"cursor": "not-allowed"}).attr("state","false");
                return
            }
            $(this).next().empty();
        $(".moco-btn-login").css({"cursor": "pointer"}).removeAttr("disabled");
        $(".js-signin-send").css({"cursor": "pointer"}).attr("state","true");
    });
    $("#login-phone").blur(function () {
        if(!phoneCheck($(this))){
            return
        }
    })
    $("#login-pwd").blur(function () {
        pwdCheck($(this));
    })
    $("#login-checkno").blur(function () {
        checkNoCheck($(this));
    });
    $("#register-phone").blur(function () {
        if(phoneCheck($(this))){
            var r = checkUser($(this).val());
            if (r.result=="success"){
                $(this).next().empty().text("账号已存在，请登录").css({"visibility":"visible"});
                $("#moco-btn-register").css({"cursor": "not-allowed"}).attr("disabled","disabled")
                return false;
            }
            $(this).next().css({"visibility":"hidden"});
            $("#moco-btn-register").css({"cursor": "pointer"}).removeAttr("disabled");
        }
    });
    $("#register-pictureCheck").blur(function () {
        pictureCheck();
    });
    //登录按钮点击事件
    $(".moco-btn-login").click(function () {
        if (phoneCheck($("#login-phone"))){
            if ($(".js-loginPassword").css("display")=="block"){
                if (!pwdCheck($("#login-pwd"))){
                    return
                }
            }else {
                if (!checkNoCheck($("#login-checkno"))){
                    return
                }
            }
            if ($(this).attr("loginway")=="code"){
                codeLogin($("#login-globle-error"))
            }else {
                pwdLogin($("#login-phone").val(),$("#login-pwd").val())
            }
        }
    });

    //注册按钮
    $("#moco-btn-register").click(function () {
        if (phoneCheck($("#register-phone")) && pictureCheck()){
            var s = $(".auto-cbx").prop("checked");
            if(!s){
                $("#signin-globle-error").empty().text("请同意注册协议").css({"visibility":"visible"});
                return;
            }
            if ((sendCheckNo($("#register-phone").val()))=="OK") {
                flushTime($(".js-register-send"));
                $("#signin-globle-error").empty().css({"visibility":"hidden"});
                $(".js-phoneNumber").empty().text($("#register-phone").val());
                register1();
            }else {
                $("#signin-globle-error").empty().text("一个号码禁止在60秒内重复发送请求").css({"visibility":"visible"})
                return;
            }
        }
    });
    //完成按钮
    $(".moco-btn-register1").click(function () {
        if (checkNoCheck($("#register-checkno")) && pwdCheck($("#register-pwd"))){
            //获取表单对象
            var jsonForm = $("#signin-form").serializeArray();
            jsonForm[0]={"name":"phone","value":""+$(".js-phoneNumber").text()+""}
            var jsonData = {}
            $.each(jsonForm,function(k,v){
                jsonData[v.name]=v.value
            })
            var param = JSON.stringify(jsonData);
            var r = {};
            $.ajax({
                url:"/user/"+$("#register-checkno").val()+"",
                type:"post",
                data:param,
                async:false,
                dataType:"json",
                contentType:"application/json",
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success:function (result) {
                    r=result;
                }
            })
            if (r.result=="fail"){
                $("#register-checkno").next().empty().text("验证码错误").css({"visibility":"visible"});
                return
            }else if(r.result=="success"){
                $(".reg-success1").show().siblings().hide();
                return
            }
            $("#register-checkno").next().empty().text("服务器错误").css({"visibility":"visible"});
            return
        }
    });

    //注册-验证码发送按钮
    $(".js-register-send").click(function () {
        $(this).attr("disabled","disabled");
        flushTime($(this));
        sendCheckNo($(".js-phoneNumber").text())
    });
    //登录-验证码发送按钮
    $(".js-signin-send").click(function () {
        if (phoneCheck($("#login-phone"))){
            $(this).attr("disabled","disabled");
            flushTime($(this));
            sendCheckNo($("#login-phone").val())
        }
    });

    $("#register-pwd").blur(function () {
        pwdCheck($(this));
    });
    $("#register-checkno").blur(function () {
        checkNoCheck($(this));
    });

    //60秒后重新发送验证请求
    function flushTime(e) {
        var wait=60;
        timer = setInterval(function(){
            if (wait==60){
                e.removeAttr("disabled")
            }
            if(wait==0){
                e.text('获取验证码');
                e.attr("state","true")
                clearInterval(timer)
            }else{
                wait--;
                e.text("重新发送 "+wait);
            }
        },1000);
    }
    $(".backNotify").click(function () {
        register();
    });
    //发送短信验证码请求
    function sendCheckNo(phone) {
        var mes = "";
        $.ajax({
            url:"/user/getphonelogincode/"+phone+"",
            type: "get",
            async:false,
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success:function (result) {
               mes= result.message;
            }
        })
        return mes;
    }
    //短信验证登录请求
    function codeLogin(e) {
        $.ajax({
            url:'/user/phonelogin/'+$("#login-checkno").val()+'&'+$("#login-phone").val()+'',
            type:"get",
            dataType:"JSON",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success:function (result) {
                if (result.result=="success"){
                    var t = 0;//cookie存储的时间

                    if ($(".auto-login").prop("checked")) {//是否选中7天免登录
                        t=7;
                    }
                    cookie.set("Authorization",result.message,t);
                    window.location.reload()
                }else{
                    e.empty().text(result.message).css({"visibility":"visible"});
                }
            }
        })
    }
    //密码登录请求
    function pwdLogin(phone,pwd) {
        $.ajax({
            url:"/user/pwdlogin/" + pwd + "&" + phone + "",
            type:"get",
            dataType:"json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success:function (result) {
                if (result.result == "fail") {
                    $(".moco-btn-login").parent().prev().empty().text(result.message).css({"visibility": "visible"});
                    return
                }
                var t = 0;//cookie存储的时间

                if ($(".auto-login").prop("checked")) {//是否选中7天免登录
                    t = 7;
                }
                cookie.set("Authorization", result.message, t);
                window.location.reload()
            }
        })
    }
    //操作cookie
    var cookie = {
        set:function(key,val,time){//设置cookie方法
            var expiresDays = time;  //将date设置为n天以后的时间
            var date = new Date(Date.now() + expiresDays*24*60*60*1000)
            var cookie = `${key}=${escape(val)};`
            if (time>0){
                cookie +=`expires=${date.toGMTString()}`
            }
            document.cookie = cookie

        },
        get:function(key) {//获取cookie方法
            /*获取cookie参数*/
            var getCookie = document.cookie;//.replace(/[ ]/g, "");  //获取cookie，并且将获得的cookie格式化，去掉空格字符
            var arrCookie = getCookie.split(";")  //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中
            var tips;  //声明变量tips
            for (var i = 0; i < arrCookie.length; i++) {   //使用for循环查找cookie中的tips变量
                var arr = arrCookie[i].split("=");   //将单条cookie用"等号"为标识，将单条cookie保存为arr数组
                if (key == arr[0]) {  //匹配变量名称，其中arr[0]是指的cookie名称，如果该条变量为tips则执行判断语句中的赋值操作
                    tips = arr[1];   //将cookie的值赋给变量tips
                    break;   //终止for循环遍历
                }
            }
            return tips;
        },
        delete:function(key){ //删除cookie方法
            var date = new Date(); //获取当前时间
            date.setTime(date.getTime()-10000); //将date设置为过去的时间
            document.cookie = key + "=v; expires =" +date.toGMTString();//设置cookie
        }
    }

    //验证用户是否纯在
    function checkUser(phone,e) {
        var r = {};
        $.ajax({
            type:"get",
            url:"/user/user/"+phone+"",
            async:false,
            dataType:"json",
            success:function (result) {
                r = result;
            }
        })
        return r;
    }
    /******************************************图片验证码的生成**/
    /**生成一个随机数**/
    function randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
    }
    /**生成一个随机色**/
    function randomColor(min, max) {
        var r = randomNum(min, max);
        var g = randomNum(min, max);
        var b= randomNum(min, max);
        return "rgb(" + r + "," + g + "," + b + ")";
    }
    var code=drawPic();
    document.getElementById("changeImg").onclick = function(e) {
        e.preventDefault();
        code=drawPic();
    }

    /**绘制验证码图片**/
    function drawPic() {
        var canvas = document.getElementById("canvas");
        var width = canvas.width;
        var height = canvas.height;
        //获取该canvas的2D绘图环境
        var ctx = canvas.getContext('2d');
        ctx.textBaseline ='bottom';
        /**绘制背景色**/
        ctx.fillStyle = randomColor(180,240);
        //颜色若太深可能导致看不清
        ctx.fillRect(0,0,width,height);
        /**绘制文字**/
        var str ='ABCEFGHJKLMNPQRSTWXY123456789';

        var code="";
        //生成四个验证码
        for(var i=1;i<=4;i++) {
            var txt = str[randomNum(0,str.length)];
            code=code+txt;
            ctx.fillStyle = randomColor(50,160);
            //随机生成字体颜色
            ctx.font = randomNum(15,40) +'px SimHei';
            //随机生成字体大小
            var x =10 +i *25;
            var y = randomNum(25,35);
            var deg = randomNum(-45,45);
            //修改坐标原点和旋转角度
            ctx.translate(x, y);
            ctx.rotate(deg * Math.PI /180);
            ctx.fillText(txt,0,0);
            //恢复坐标原点和旋转角度
            ctx.rotate(-deg * Math.PI /180);
            ctx.translate(-x, -y);
        }

        /**绘制干扰线**/
        for(var i=0;i<3;i++) {
            ctx.strokeStyle = randomColor(40, 180);
            ctx.beginPath();
            ctx.moveTo(randomNum(0,width/2), randomNum(0,height/2));
            ctx.lineTo(randomNum(0,width/2), randomNum(0,height));
            ctx.stroke();
        }
        /**绘制干扰点**/
        for(var i=0;i <50;i++) {
            ctx.fillStyle = randomColor(255);
            ctx.beginPath();
            ctx.arc(randomNum(0, width), randomNum(0, height),1,0,2* Math.PI);
            ctx.fill();
        }
        return code;
    }



//    检查本地是否存储用户信息的cookie
    isLogin();
    function isLogin(){
        var token = cookie.get("Authorization");
        if (token!=null && token!=""){
            $("#header-user-card").show().next().hide();
            return
        }
        $("#header-user-card").hide().next().show();
    }
    //退出按钮点
    $(".card-sets a").click(function () {
        cookie.delete("Authorization");
        window.location.reload();
    })
})